package servlets;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Mobile_ucServlet extends HttpServlet {
    private static final long serialVersionUID = -8608034654794572382L;


    public void init() {
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                        // Check for request source
    String request_source = request.getParameter("request_source");
    String username = request.getParameter("username");
    String file=null;
    if(username.equalsIgnoreCase("nuno"))
         file = "/xmldata/classes_nuno.xml";
    else if(username.equalsIgnoreCase("gilmeyer"))
         file = "/xmldata/classes_gil.xml";
    else if(username.equalsIgnoreCase("vasco"))
         file = "/xmldata/classes_vasco.xml";
    else if(username.equalsIgnoreCase("Aula 1"))
         file = "/xmldata/material_MRC.xml";
     else if(username.equalsIgnoreCase("Aula 2"))
         file = "/xmldata/material_IS.xml";

    if (file == null || file.equals(""))throw new ServletException("Invalid or non-existent file parameter in UrlServlet servlet.");
    
    URL url = null;
    URLConnection urlConn = null;
    PrintWriter out = null;
    BufferedInputStream buf = null;
    try {
          out = response.getWriter();
          url = getServletContext().getResource(file);
          //set response header
          response.setContentType("text/xml");
          response.setStatus(response.SC_OK);
          urlConn = url.openConnection();
          //establish connection with URL presenting web.xml
          urlConn.connect();
          buf = new BufferedInputStream(urlConn.getInputStream());
          int readBytes = 0;
          while ((readBytes = buf.read()) != -1)
            out.write(readBytes);
    } catch (MalformedURLException mue) {
      throw new ServletException(mue.getMessage());
    } catch (IOException ioe) {
      throw new ServletException(ioe.getMessage());
    } finally {
      if (out != null)
        out.close();
      if (buf != null)
        buf.close();
    }
  
    }

     
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {	       
        processRequest(request, response);
       
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
	doGet(request, response);
    }

}